package ar.edu.unlu.sistemas.ws.business;

import java.util.HashMap;

public class IndexManager {
	
	private static IndexManager instance;
	private HashMap<String,ResourceDescriptionWS> peersDescriptions = new HashMap<String,ResourceDescriptionWS>();
	
	private IndexManager() {
		
	}
	
	public static IndexManager getInstance() {
		if (instance == null) instance = new IndexManager();
		return instance;
	}
	
	public synchronized Integer putDescription(PeerWS peer, ResourceDescriptionWS description) {
		if (peer.getId() != null) {
			this.peersDescriptions.put(peer.getId(), description);
			return new Integer(peer.getId());
		} else return -1;
	}
	
	public synchronized Integer addSubDescription(PeerWS peer, ResourceDescriptionWS description) {
		if (description != null) {
			if (peer.getId() != null && this.peersDescriptions.containsKey(peer.getId())) {
				ResourceDescriptionWS resourceDescription = this.peersDescriptions.get(peer.getId());
				resourceDescription.add(description);
				return new Integer(peer.getId());
			} else return -1;
		} else return -1;
	}
	
	public synchronized Integer getDocumentFrecuency(String peerId , String word) {
		if ( this.peersDescriptions.containsKey(peerId)) {
			ResourceDescriptionWS description = this.peersDescriptions.get(peerId);
			if (description.getResourceDescription().containsKey(word)) return description.getResourceDescription().get(word);
			else return 0;
		} else return 0;
	}
	
	public synchronized Integer getNumberOfDocs(String peerId) {
		if ( this.peersDescriptions.containsKey(peerId)) return this.peersDescriptions.get(peerId).getnDocs();
		else return 0;
	}
	
	public synchronized Integer getNumberOfTerms(String peerId) {
		if ( this.peersDescriptions.containsKey(peerId)) return this.peersDescriptions.get(peerId).getResourceDescription().size();
		else return 0;
	}
	
	public synchronized Float getAverageNumberOfTerms(){
		Float ac = new Float(0);
		for (String peerId : this.peersDescriptions.keySet()) ac+= this.peersDescriptions.get(peerId).getResourceDescription().size();
		if (this.peersDescriptions.size() > 0) return ac/this.peersDescriptions.size();
		else return ac;
	}
	
	public synchronized Integer getNumberOfResourcesWithTerm(String word) {
		Integer ac = new Integer(0);
		for (String peerId : this.peersDescriptions.keySet()) ac+= this.peersDescriptions.get(peerId).getResourceDescription().containsKey(word) ? 1 : 0;
		return ac;
	}

}
